//
//  overload_subscript_operate.hpp
//  learnC++
//
//  Created by apple on 2018/6/5.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#ifndef overload_subscript_operate_hpp
#define overload_subscript_operate_hpp

#include <stdio.h>
#include <iostream>

//    下标运算符通常被重载以提供对类中包含的数组（或其他类似结构）中的单个元素的直接访问。 因为字符串通常以字符数组的形式实现，所以operator []通常在字符串类中实现，以允许用户访问字符串的单个字符。
class IntList
{
private:
    int * m_list;
    
public:
    IntList(int value);
    ~IntList();
    
    //你甚至可以在[]中间加字符串，虽然很蠢
//    void operator[] (std::string index);
    
    //非const对象访问
    int& operator[] (const int index);// for non-const objects: can be used for assignment
    //const对象访问（返回的是const对象）
    const int& operator[] (const int index) const;// for const objects: can only be used for access

};


/*
 
 IntList list(4);
 list[2] = 3; // okay: calls non-const version of operator[]
 std::cout << list[2];
 
 const IntList clist(4);
 clist[2] = 3; // compile error: calls const version of operator[], which returns a const reference.  Cannot assign to this.
 std::cout << clist[2];
 
 
 NOTE:数组对象[]与对象的[]不冲突
 
 IntList *list = new IntList;
 list [2] = 3; // error: this will assume we're accessing index 2 of an array of IntLists
 delete list;
 
 
 IntList *list = new IntList;
 (*list)[2] = 3; // get our IntList object, then call overloaded operator[]
 delete list;
 
 */

#endif /* overload_subscript_operate_hpp */
